#!/usr/bin/env python3
"""
模拟交易启动脚本
用于启动OKX模拟盘实时交易
"""

import asyncio
import sys
import signal
from pathlib import Path
from typing import Dict, List
from datetime import datetime

# 添加项目根目录到Python路径
project_root = Path(__file__).parent.parent
sys.path.insert(0, str(project_root))

from xcquant.core import unified_core, unified_logger
from xcquant.trading.trading_engine import TradingEngine
from xcquant.exchanges.okx import OKXExchange
from xcquant.web.app import WebApp
from grid_strategy_demo import GridStrategy


class DemoTradingManager:
    """模拟交易管理器"""
    
    def __init__(self, config_path: str):
        self.config_path = config_path
        self.logger = unified_logger.get_logger(__name__)
        self.trading_engine = None
        self.web_app = None
        self.strategies: List[GridStrategy] = []
        self.running = False
        
    async def initialize(self):
        """初始化交易管理器"""
        self.logger.info("初始化模拟交易管理器...")
        
        # 加载配置
        unified_core.load_config(self.config_path)
        
        # 创建交易引擎
        self.trading_engine = TradingEngine()
        await self.trading_engine.initialize()
        
        # 创建Web应用
        self.web_app = WebApp()
        await self.web_app.initialize()
        
        self.logger.info("模拟交易管理器初始化完成")
        
    async def create_strategies(self):
        """创建交易策略"""
        self.logger.info("创建交易策略...")
        
        # BTC网格策略配置
        btc_config = {
            'name': 'BTC模拟网格',
            'symbol': 'BTC-USDT',
            'exchange': 'okx',
            'type': 'spot',
            'grid_count': 3,              # 减少网格数量，适合演示
            'price_range_percent': 0.01,  # 1%价格范围
            'base_order_size': 5.0,       # 5 USDT每单
            'profit_ratio': 0.002,        # 0.2%利润目标
            'stop_loss_ratio': 0.01,      # 1%止损
            'max_position_ratio': 0.1,    # 最大10%仓位
            'enabled': True
        }
        
        # 创建BTC策略
        btc_strategy = GridStrategy(btc_config)
        await btc_strategy.initialize()
        self.strategies.append(btc_strategy)
        
        # 注册策略到交易引擎
        await self.trading_engine.add_strategy(btc_strategy)
        
        self.logger.info(f"已创建 {len(self.strategies)} 个策略")
        
    async def start_trading(self):
        """启动交易"""
        self.logger.info("启动模拟交易...")
        
        self.running = True
        
        # 启动交易引擎
        await self.trading_engine.start()
        
        # 启动Web服务器（非阻塞）
        web_task = asyncio.create_task(self.web_app.run_async())
        
        # 主交易循环
        try:
            while self.running:
                # 更新策略状态
                await self._update_strategies()
                
                # 检查系统状态
                await self._check_system_status()
                
                # 等待一段时间
                await asyncio.sleep(10)  # 每10秒检查一次
                
        except KeyboardInterrupt:
            self.logger.info("收到停止信号，正在关闭...")
        finally:
            await self.stop_trading()
            web_task.cancel()
            
    async def _update_strategies(self):
        """更新策略状态"""
        for strategy in self.strategies:
            try:
                # 获取最新市场数据
                ticker = await strategy.exchange.get_ticker(strategy.symbol)
                
                # 模拟tick数据
                tick_data = {
                    'symbol': strategy.symbol,
                    'price': ticker['last'],
                    'volume': ticker['volume'],
                    'timestamp': datetime.now().timestamp()
                }
                
                # 发送给策略处理
                await strategy.on_tick(tick_data)
                
            except Exception as e:
                self.logger.error(f"更新策略 {strategy.name} 失败: {e}")
                
    async def _check_system_status(self):
        """检查系统状态"""
        try:
            # 检查交易引擎状态
            engine_status = await self.trading_engine.get_status()
            
            # 检查策略状态
            for strategy in self.strategies:
                metrics = await strategy.calculate_metrics()
                self.logger.info(f"策略 {strategy.name}: 活跃订单={metrics.get('active_orders', 0)}")
                
        except Exception as e:
            self.logger.error(f"检查系统状态失败: {e}")
            
    async def stop_trading(self):
        """停止交易"""
        self.logger.info("停止模拟交易...")
        
        self.running = False
        
        # 停止所有策略
        for strategy in self.strategies:
            try:
                await strategy.stop()
            except Exception as e:
                self.logger.error(f"停止策略失败: {e}")
                
        # 停止交易引擎
        if self.trading_engine:
            await self.trading_engine.stop()
            
        self.logger.info("模拟交易已停止")
        
    def show_status(self):
        """显示当前状态"""
        print("\n" + "="*60)
        print("📊 模拟交易状态")
        print("="*60)
        
        print(f"🔄 运行状态: {'运行中' if self.running else '已停止'}")
        print(f"📈 活跃策略: {len(self.strategies)}")
        
        if self.strategies:
            print("\n策略详情:")
            for i, strategy in enumerate(self.strategies, 1):
                print(f"  {i}. {strategy.name}")
                print(f"     交易对: {strategy.symbol}")
                print(f"     状态: {'运行中' if strategy.enabled else '已停止'}")
                
        print(f"\n🌐 Web界面: http://127.0.0.1:5001")
        print(f"🔌 API接口: http://127.0.0.1:8001")
        print("\n💡 提示:")
        print("- 按 Ctrl+C 停止交易")
        print("- 查看日志: ./logs/")
        print("- 交易记录: ./demo_results/")


async def main():
    """主函数"""
    print("🚀 启动OKX模拟交易")
    print("="*50)
    
    config_path = project_root / "config_okx_demo.yaml"
    
    # 创建交易管理器
    manager = DemoTradingManager(str(config_path))
    
    # 设置信号处理
    def signal_handler(signum, frame):
        print("\n收到停止信号，正在安全关闭...")
        manager.running = False
        
    signal.signal(signal.SIGINT, signal_handler)
    signal.signal(signal.SIGTERM, signal_handler)
    
    try:
        # 初始化
        await manager.initialize()
        print("✅ 交易管理器初始化完成")
        
        # 创建策略
        await manager.create_strategies()
        print("✅ 交易策略创建完成")
        
        # 显示状态
        manager.show_status()
        
        # 启动交易
        print("\n🔄 启动模拟交易...")
        await manager.start_trading()
        
    except Exception as e:
        print(f"❌ 启动失败: {e}")
        import traceback
        traceback.print_exc()
    finally:
        print("👋 模拟交易已结束")


if __name__ == "__main__":
    asyncio.run(main())